import RequestMethod from '../api/request-method';
import { del, get, post, put } from '../request';

const requestHandlerMapping = {
  [RequestMethod.GET]: get,
  [RequestMethod.POST]: post,
  [RequestMethod.PUT]: put,
  [RequestMethod.DELETE]: del,
};

/**
 * 执行请求
 *
 * @param uri 请求URI
 * @param method 请求方法
 * @param apiRequest 请求信息
 */
export function executeRequest<T = unknown, D extends Recordable = Recordable>(
  uri: string,
  method: RequestMethod,
  apiRequest?: ApiRequest<D>,
): Promise<ApiResponse<T>> {
  if (method == RequestMethod.GET || method == RequestMethod.DELETE) {
    return requestHandlerMapping[method].call(undefined, uri, apiRequest?.params, apiRequest?.headers) as Promise<
      ApiResponse<T>
    >;
  }

  return requestHandlerMapping[method].call(
    undefined,
    uri,
    apiRequest?.data,
    apiRequest?.params,
    apiRequest?.headers,
  ) as Promise<ApiResponse<T>>;
}
